const CryptoJS = require("crypto-js");
const AES = require("crypto-js/aes");


/** AES加密 */
export function encrypt(word, keyStr, ivStr) {
    try {
        let key = CryptoJS.enc.Utf8.parse(keyStr);
        let iv = CryptoJS.enc.Utf8.parse(ivStr);

        let srcs = CryptoJS.enc.Utf8.parse(JSON.stringify(word));
        var encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            // mode: CryptoJS.mode.CBC,
            // padding: CryptoJS.pad.ZeroPadding
        });

        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    } catch(err) {
        $global.message.error({ content: "加密失败" });
    }
}


/** AES 解密 */
export function decrypt(word, keyStr, ivStr) {
    try {
        let key = CryptoJS.enc.Utf8.parse(keyStr);
        let iv = CryptoJS.enc.Utf8.parse(ivStr);

        let base64 = CryptoJS.enc.Base64.parse(word);
        let src = CryptoJS.enc.Base64.stringify(base64);

        var decrypt = CryptoJS.AES.decrypt(src, key, {
            iv: iv,
            // mode: CryptoJS.mode.CBC,
            // padding: CryptoJS.pad.ZeroPadding
        });

        var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        let str = decryptedStr.toString();
        return JSON.parse(str);
    } catch(err) {
        $global.message.error({ content: "解密失败" });
    }
}


export function SHA256 (data) {
    try {
        const message = typeof data === "object" ? JSON.stringify(data) : String(data);
        return CryptoJS.SHA256(message).toString();
    } catch (error) {
        console.error("SHA256 hash error:", error);
        return null;
    }
}






// let key = "mZyFG92Qq8GQ9DnY";
// let iv = "mZyFG92Qq8GQ9Dn1";
// let jiamiData = encrypt(JSON.stringify({
//     a: 1,
//     b: 2,
//     c: 3
// }), key, iv); //加密
// console.log(jiamiData);


// let jiemiData = decrypt(jiamiData, key, iv); //解密
// console.log(jiemiData);



